package com.gtw.modules.sys.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.CollectionType;
import com.gtw.common.annotation.SysLog;
import com.gtw.common.utils.*;
import com.gtw.common.validator.Assert;
import com.gtw.dto.TbOrderDto;
import com.gtw.modules.api.service.TbAddressService;
import com.gtw.modules.api.service.TbCommodityService;
import com.gtw.modules.api.service.TbShoppingCartServices;
import com.gtw.modules.api.service.TbUserService;
import com.gtw.modules.base.service.TbCityService;
import com.gtw.modules.base.service.TbDistrictService;
import com.gtw.modules.base.service.TbProvinecService;
import com.gtw.modules.dao.TbExpressCodeDao;
import com.gtw.modules.entity.*;
import com.gtw.modules.sys.service.SysTbOrderService;
import com.gtw.modules.sys.service.TbExpressCodeService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 订单controller
 *
 * @author wuye
 * @date 2018/1/29
 */
@RestController
@RequestMapping("/sys/order")
public class SysTbOrderController extends AbstractController {

    @Autowired
    private SysTbOrderService orderService;

    @Autowired
    private TbAddressService tbAddressService;

    @Autowired
    private TbShoppingCartServices tbShoppingCartServices;

    @Autowired
    private TbCityService tbCityService;

    @Autowired
    private TbDistrictService tbDistrictService;

    @Autowired
    private TbProvinecService tbProvinecService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    @RequiresPermissions("sys:order:list")
    public R list(@RequestParam Map<String, Object> params) {
        //查询列表数据
        Query query = new Query(params);

        List<TbOrder> orderList = orderService.queryList(query);
        int total = orderService.queryTotal(query);

        PageUtils pageUtil = new PageUtils(orderList, total, query.getLimit(), query.getPage());

        return R.ok().put("page", pageUtil);
    }


    /**
     * 导出excel表格
     */
    @RequestMapping(value = "/excel",method = RequestMethod.GET)
    @RequiresPermissions("sys:order:list")
    public void excel(String orderstatus, HttpServletResponse response) throws IOException {
        //只查询30天以内的数据
        LocalDateTime now=LocalDateTime.now();
        LocalDateTime time = now.minus(30, ChronoUnit.DAYS);
        Date startTime = Date.from(time.atZone(ZoneId.systemDefault()).toInstant());
        //查询列表数据
        List<TbOrderDto> orderList = orderService.queryListLinkAddress(orderstatus,startTime);
        Workbook workbook=new XSSFWorkbook();
        Sheet sheet = workbook.createSheet();
        createHeaders(sheet);
        int lineNum=1;
        for (TbOrderDto order:orderList){
            String goodsDesc=buildGoodsDesc(order.getShoppingcartid());
            Row row = sheet.createRow(lineNum);
            addDateRow(row,order,goodsDesc);
            lineNum++;
        }
        setResponseHeader(response,"订单列表统计.xlsx");
        ServletOutputStream outputStream = response.getOutputStream();
        workbook.write(outputStream);
        outputStream.flush();
        outputStream.close();
    }

    public void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 往excel表格里面行写入数据
     * @param row
     * @param order
     * @param goodsDesc
     */
    private void addDateRow(Row row, TbOrderDto order, String goodsDesc) {
        Cell cell = row.createCell(0, CellType.STRING);
        cell.setCellValue(order.getBillno());
        Cell cell1 = row.createCell(1, CellType.STRING);
        cell1.setCellValue(order.getAddressuser());
        Cell cell2 = row.createCell(2, CellType.STRING);
        cell2.setCellValue(order.getAddressphone());
        String address = order.getProvincename() + " " + order.getCityname() + " " + order.getDistrictname()+" "+order.getAddressdetails();
        Cell cell3 = row.createCell(3, CellType.STRING);
        cell3.setCellValue(address);
        Cell cell4 = row.createCell(4, CellType.STRING);
        cell4.setCellValue(goodsDesc);
        Cell cell5 = row.createCell(5, CellType.STRING);
        cell5.setCellValue(String.valueOf(order.getTotalfee()/100d));

        Cell cell6 = row.createCell(6, CellType.STRING);
        cell6.setCellValue(order.getRemark());
        Cell cell7 = row.createCell(7, CellType.STRING);
        cell7.setCellValue(DateUtils.format(order.getCreatedate()));
    }

    /**
     * 将商品明细格式化为字符串
     * @param shoppingcartid
     * @return
     */
    private String buildGoodsDesc(String shoppingcartid) {
        StringBuilder stringBuilder = new StringBuilder();
        JSONArray ja = JSONArray.fromObject(shoppingcartid);
        for (int i = 0; i < ja.size(); i++) {
            TbShoppingCart tbShoppingCart = tbShoppingCartServices.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString()));
            stringBuilder.append("名称:"+tbShoppingCart.getCommodityname());
            String selected = tbShoppingCart.getSelected();
            if (StringUtils.isNotBlank(selected)){
                //拼接商品的规格参数
                joinGoodsModel(stringBuilder,selected);
            }
            stringBuilder.append(",");
            stringBuilder.append("数量:"+tbShoppingCart.getCommoditynumber());
            stringBuilder.append("\r\n");
        }
        return stringBuilder.toString();
    }

    /**
     * 拼接商品规格参数
     * @param stringBuilder
     * @param selected
     */
    private void joinGoodsModel(StringBuilder stringBuilder, String selected) {
        stringBuilder.append("(");
        ObjectMapper objectMapper=new ObjectMapper();
        CollectionType collectionType = objectMapper.getTypeFactory().constructCollectionType(List.class, Map.class);
        try {
            List<Map<String,Object>> goodsModels = objectMapper.readValue(selected, collectionType);
            for (Map<String,Object> goodsModel:goodsModels){
                stringBuilder.append(goodsModel.get("propertyname"));
                stringBuilder.append(":");
                stringBuilder.append(goodsModel.get("propertyvalue"));
                stringBuilder.append(",");
            }
            stringBuilder.append(")");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 创建表格列头
     * @param sheet
     */
    private void createHeaders(Sheet sheet) {
        //业务单号	收件人姓名	收件人手机	地址	商品明细	买家备注	购买时间
        Row row = sheet.createRow(0);
        Cell cell = row.createCell(0, CellType.STRING);
        cell.setCellValue("业务单号");
        Cell cell1 = row.createCell(1, CellType.STRING);
        cell1.setCellValue("收件人姓名");
        Cell cell2 = row.createCell(2, CellType.STRING);
        cell2.setCellValue("收件人手机");
        Cell cell3 = row.createCell(3, CellType.STRING);
        cell3.setCellValue("地址");
        Cell cell4 = row.createCell(4, CellType.STRING);
        cell4.setCellValue("商品明细");
        Cell cell5 = row.createCell(5, CellType.STRING);
        cell5.setCellValue("金额");
        Cell cell6 = row.createCell(6, CellType.STRING);
        cell6.setCellValue("买家备注");
        Cell cell7 = row.createCell(7, CellType.STRING);
        cell7.setCellValue("购买时间");
    }


    /**
     * 信息
     */
    @RequestMapping("/info/{id}")
    @RequiresPermissions("sys:order:info")
    public R info(@PathVariable("id") Integer id) {
        TbOrder order = orderService.queryObject(id);
        order.setTotalfee(order.getTotalfee() / 100);

        String address=tbAddressService.fromIdToDetail(order.getAddressid());
        TbAddress tbAddress = tbAddressService.queryObject(order.getAddressid());
        address+=" 收货人:"+tbAddress.getUsername()+" "+"联系电话:"+tbAddress.getPhone();
        String path = order.getShoppingcartid();
        JSONArray ja = JSONArray.fromObject(path);
        List<TbShoppingCart> list = new ArrayList<>();
        for (int i = 0; i < ja.size(); i++) {
            TbShoppingCart tbShoppingCart = tbShoppingCartServices.selectByPrimaryKey(Integer.parseInt(ja.get(i).toString()));
            list.add(tbShoppingCart);
        }
        return R.ok().put("order", order).put("address", address).put("list", list);
    }

    /**
     * 保存
     */
    @SysLog("添加")
    @RequestMapping("/save")
    @RequiresPermissions("sys:order:save")
    public R save(@RequestBody TbOrder order) {
        orderService.save(order);

        return R.ok();
    }

    /**
     * 修改
     */
    @SysLog("修改")
    @RequestMapping("/update")
    @RequiresPermissions("sys:order:update")
    public R update(@RequestBody TbOrder order) {
        order.setUpdateuser(getUser().getUsername());
        order.setUpdatedate(new Date());
        orderService.update(order);

        return R.ok();
    }

    /**
     * 删除（软删除）
     */
    @SysLog("删除")
    @RequestMapping("/delete")
    @RequiresPermissions("sys:order:delete")
    public R delete(@RequestBody Integer[] ids) {
        for (int i = 0; i < ids.length; i++) {
            TbOrder tbOrder = orderService.queryObject(ids[i]);
            tbOrder.setIsdelete(true);
            orderService.update(tbOrder);
        }
        return R.ok();
    }

    @Autowired private TbUserService tbUserService;
    @Autowired private TbExpressCodeDao tbExpressCodeDao;
    /**
     * 发货
     *
     * @return
     */
    @SysLog("发货")
    @RequestMapping("/fahuo")
    public R fahuo(@RequestBody TbOrder order) {
        TbOrder tbOrder = orderService.queryBybillno(order.getBillno());
        tbOrder.setWuliutype(order.getWuliutype());
        tbOrder.setWuliuorderno(order.getWuliuorderno());
        tbOrder.setOrderstatus(PayStatus.delivering.getName());
        tbOrder.setUpdatedate(new Date());
        tbOrder.setUpdateuser(getUser().getUsername());
        orderService.update(tbOrder);
        TbUser tbUser = tbUserService.queryByUid(tbOrder.getUid());
        TbExpressCode expressCode=tbExpressCodeDao.findByCode(tbOrder.getWuliutype());

        String address = tbAddressService.fromIdToDetail(tbOrder.getAddressid());

        WeiXinMsgUtil.sendDeliverMsg(tbUser.getWxopenid(),buildGoodsDesc(tbOrder.getShoppingcartid()),expressCode.getCom(),tbOrder.getWuliuorderno(),address);
        return R.ok();
    }
}
